import { encryptedData, isLogin } from '@/utils/utils';
import '@ant-design/compatible/assets/index.css';
import { Button, Checkbox, Form, Input, message, Modal, notification } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import React, { Component } from 'react';
import router from 'umi/router';
import { publicKey } from '../../../../public/global';
import PageLoading from '../../../components/PageLoading';
import styles from './style.less';
import quote from '../../../assets/quote.png';
import debounce from 'lodash/debounce';
import UpdatePassword from './updatePassword';
import ValidateEmial from './validateEmail';
import BoundEmail from './boundEmail'
import { InfoCircleOutlined } from '@ant-design/icons'
const FormItem = Form.Item;
class Login extends Component<any, any> {
  formRef = React.createRef<FormInstance>();
  containerRef = React.createRef();
  constructor(props: any) {
    super(props);
    this.state = {
      isPass: false,
      isVerified: true,
      currentShow: 1,
      isShowVerified: false,
      formWrapperWidth: 480,
      captchaImage: null, //验证码gif图片
      keyCode: null, //验证码code
      accountName: undefined
    };
    this.resizeUpdate = debounce(this.resizeUpdate, 500);
  }

  // 密码到期提醒
  pwdExpiresNotice(dayNum: number) {
    if(!isNaN(dayNum) && dayNum > 0 && dayNum <= 5) {
      notification.warning({
        message: '密码到期提示',
        description:`您的密码还有${dayNum}天过期失效，请及时修改密码！`,
        duration: 0,
      });
    }
  }

  componentDidMount(): void {
    this.fetchCode();
    document.onkeydown = this.keydown;
    if (isLogin()) {
      let pwdValidityPeriod = sessionStorage.getItem('pwdValidityPeriod');
      this.pwdExpiresNotice(Number(pwdValidityPeriod));
      router.push('/');
    }
    // this.resizeUpdate();
    // window.addEventListener('resize', this.resizeUpdate);
  }
  componentWillUnmount(): void {
    // window.removeEventListener('resize', this.resizeUpdate);
  }
  resizeUpdate = () => {
    this.setState({
      formWrapperWidth: this.containerRef.current?.scrollWidth,
    });
    // const $verify = this.refs.verify as ReactSimpleVerify;
    // $verify?.reset();
    // this.setState({ isPass: false });
  };
  keydown = (e: any) => {
    let currKey = 0;
    currKey = e.keyCode || e.which || e.charCode; // 支持IE、FF
    if (currKey == 13) {
      this.handleSubmit();
    }
  };

  onFinish = (values: any) => {
    const { dispatch } = this.props;
    const { currentShow, isPass, isShowVerified, keyCode } = this.state;
    const submitData = { ...values, captchaKey: keyCode };
    if (!values.userCaptchaValue || values.userCaptchaValue.trim() === '') {
      message.warning('验证码不能为空！');
      return;
    };

    submitData.accountPwd = encryptedData(submitData.accountPwd, publicKey); // 密码使用RSA加密
    submitData.accountName = encryptedData(submitData.accountName, publicKey); // 账号使用RSA加密
    if (!isShowVerified) {
      dispatch({
        type: 'login/login',
        payload: {
          pwd: values.accountPwd,
          ...submitData,
        },
        callback: (res: any) => {
          // if (res.statusCode === '9042') {
          //   this.handleCaptchaRefresh()
          //   return
          // };
          if (res.statusCode === '0') {
            if (currentShow == 1)
              this.setState({
                isPass: false,
                isVerified: true,
                currentShow: 2,
                isShowVerified: false,
                accountName: values.accountName
              });
            if (currentShow == 2)
              this.setState({
                isPass: false,
                isVerified: true,
                currentShow: 1,
                isShowVerified: false,
                accountName: values.accountName
              });
            // 踢出上次已登录信息
            if (res.data.loginResult === 2) {
              message.info('您已登录，本次登录会踢掉上次登录信息！');
            }
            if (res.data.loginResult === 3) {
              message.error('登录限制，请先注销上次登录信息再登录！');
            }
          } else {
            this.setState({ isShowVerified: false, accountName: values.accountName });
            this.handleCaptchaRefresh();
            return
          }
        },
      });
    } else {
      if (isPass) {
        dispatch({
          type: 'login/login',
          payload: {
            ...submitData,
          },
          callback: (res: any) => {
            if (res.statusCode === '0') {
              if (currentShow == 1)
                this.setState({
                  isPass: false,
                  isVerified: true,
                  currentShow: 2,
                  isShowVerified: false,
                });
              if (currentShow == 2)
                this.setState({
                  isPass: false,
                  isVerified: true,
                  currentShow: 1,
                  isShowVerified: false,
                });
            } else {
              if (currentShow == 1)
                this.setState({
                  isPass: false,
                  isVerified: true,
                  currentShow: 2,
                  isShowVerified: true,
                });
              if (currentShow == 2)
                this.setState({
                  isPass: false,
                  isVerified: true,
                  currentShow: 1,
                  isShowVerified: true,
                });
            }
          },
        });
      } else {
        // message.warn('请先完成滑动验证再登录！');
        this.setState({ isPass: false, isVerified: false, accountName: values.accountName });
      }
    }
  };

  handleSubmit = () => {
    this.formRef.current?.submit()
  };

  handleAutoLogin = (e: any) => {
    const check = e.target.checked;
    if (check) {
      localStorage.setItem('remember', 'checked');
    } else {
      localStorage.removeItem('remember');
    }
  };
  forgetPwd = (e: any) => {
    // message.warning('请联系管理员找回密码！');
    router.push('/user/forgetPassword');
  };
  onVerifySuccess = () => {
    this.setState({ isPass: true, isVerified: true });
  };

  // 获取验证码
  fetchCode = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/getData',
      payload: {
        url: '/login/getCaptcha'
      },
      callback: (res: any) => {
        const base64Image = `data:image/gif;base64,${res.data.msgCodeUrl}`;
        this.setState({ captchaImage: base64Image, keyCode: res.data.keyCode });
      },
    });
  };

  // 验证码刷新
  handleCaptchaRefresh = () => {
    this.fetchCode(); // 刷新验证码
  };
  render() {
    const { submitting, dispatch, login } = this.props;
    // const { isPass, isVerified, currentShow, isShowVerified, formWrapperWidth } = this.state;
    const { captchaImage, accountName } = this.state;
    return isLogin() ? (
      <PageLoading />
    ) : (
      // <div className={styles.login}>
      //   <div className={styles.main}>
      //     <h1 style={{ textAlign: 'center', paddingTop: 10, paddingBottom: 10 }}>欢迎登录</h1>
      //     <Form ref={this.formRef} onFinish={this.onFinish}>
      //       <FormItem
      //         name={'accountName'}
      //         rules={[{ required: true, message: '请输入登录账号！' }]}
      //       >
      //         <Input prefix={<UserOutlined />} placeholder="请输入登录账号" maxLength={30} />
      //       </FormItem>
      //       <FormItem name={'accountPwd'} rules={[{ required: true, message: '请输入登录密码！' }]}>
      //         <Input.Password
      //           prefix={<LockOutlined />}
      //           placeholder="请输入登录密码"
      //           maxLength={30}
      //         />
      //       </FormItem>
      //       {isShowVerified && currentShow == 1 ? (
      //         <FormItem>
      //           <ReactSimpleVerify
      //             movedColor="#1890FF"
      //             ref="verify"
      //             width="360"
      //             successTips="验证通过"
      //             success={this.onVerifySuccess.bind(this)}
      //           />
      //           {!isPass && !isVerified ? (
      //             <div style={{ color: '#f5222d' }}>请完成验证！</div>
      //           ) : null}
      //         </FormItem>
      //       ) : null}
      //       {isShowVerified && currentShow == 2 ? (
      //         <FormItem>
      //           <ReactSimpleVerify
      //             movedColor="#1890FF"
      //             ref="verify"
      //             width="360"
      //             successTips="验证通过"
      //             success={this.onVerifySuccess.bind(this)}
      //           />
      //           {!isPass && !isVerified ? (
      //             <div style={{ color: '#f5222d' }}>请完成验证！</div>
      //           ) : null}
      //         </FormItem>
      //       ) : null}
      //       <FormItem>
      //         <Checkbox
      //           onChange={this.handleAutoLogin}
      //           style={{ float: 'left', paddingBottom: 10 }}
      //         >
      //           7天免登录
      //         </Checkbox>
      //         {/* <Link to="/user/resetPassword" style={{ float: "right", paddingBottom: 10, color: "#2F54EB"}}>忘记密码</Link> */}
      //         <Button
      //           type="primary"
      //           loading={submitting}
      //           onClick={this.handleSubmit}
      //           style={{ marginTop: 10, width: '100%' }}
      //         >
      //           登录
      //         </Button>
      //       </FormItem>
      //     </Form>
      //   </div>
      // </div>
      <div className={styles['login-wrapper']}>
        <div className={styles['lg-image']}>
          <img src={quote} alt="" style={{ height: '48rem' }} />
        </div>
        <div className={styles['lg-container']}>
          {/* <h1 style={{ textAlign: 'center', paddingTop: 10, paddingBottom: 10 }}>欢迎登录</h1> */}
          <div className={styles['main-title']} ref={this.containerRef}>
            欢迎登录
          </div>
          <div className={styles['sub-title']}>东风车联网管理平台</div>
          <Form ref={this.formRef} onFinish={this.onFinish} className={styles['form-wrapper']}>
            <FormItem
              name={'accountName'}
              rules={[{ required: true, message: '请输入登录账号！' }]}
              className={styles['fm-input-wrapper']}
            >
              <Input
                // prefix={<UserOutlined />}
                placeholder="请输入登录账号"
                maxLength={64}
                bordered={false}
                className={styles['fm-input']}
              />
            </FormItem>
            <FormItem
              name={'accountPwd'}
              rules={[{ required: true, message: '请输入登录密码！' }]}
              className={styles['fm-input-wrapper']}
            >
              <Input.Password
                // prefix={<LockOutlined />}
                placeholder="请输入登录密码"
                maxLength={30}
                bordered={false}
                className={`${styles['fm-input']} ${styles['fm-pwd-input']}`}
              />
            </FormItem>
            <FormItem
              name={'userCaptchaValue'}
              rules={[{ required: true, message: '请输入验证码！' }]}
              className={styles['fm-input-wrapper']}
            >
              <Input
                suffix={
                  <img
                    src={captchaImage}
                    alt="验证码未加载"
                    title="点击刷新验证码"
                    onClick={this.handleCaptchaRefresh}
                    style={{ cursor: 'pointer' }}
                    className={styles['fm-captcha-image']}
                  />
                }
                autoComplete="usercode"
                placeholder="请输入验证码"
                maxLength={10}
                bordered={false}
                className={`${styles['fm-input']} ${styles['fm-input-codeSuffix']}`}
              />
            </FormItem>
            {/* {isShowVerified && currentShow == 1 ? (
              <FormItem>
                <ReactSimpleVerify
                  movedColor="#1890FF"
                  ref="verify"
                  width={formWrapperWidth}
                  barBackground={'#F9F9F9'}
                  successTips="验证通过"
                  success={this.onVerifySuccess.bind(this)}
                />
                {!isPass && !isVerified ? (
                  <div style={{ color: '#f5222d', marginTop: '6px' }}>请完成验证！</div>
                ) : null}
              </FormItem>
            ) : null} */}
            {/* {isShowVerified && currentShow == 2 ? (
              <FormItem>
                <ReactSimpleVerify
                  movedColor="#1890FF"
                  ref="verify"
                  width={formWrapperWidth}
                  barBackground={'#F9F9F9'}
                  successTips="验证通过"
                  success={this.onVerifySuccess.bind(this)}
                />
                {!isPass && !isVerified ? (
                  <div style={{ color: '#f5222d', marginTop: '6px' }}>请完成验证！</div>
                ) : null}
              </FormItem>
            ) : null} */}
            <FormItem>
              <Checkbox
                onChange={this.handleAutoLogin}
                // style={{ float: 'left', paddingBottom: 10 }}
                className={styles['fm-checkbox']}
              >
                自动登录
              </Checkbox>
              {/* <Link to="/user/resetPassword" style={{ float: "right", paddingBottom: 10, color: "#2F54EB"}}>忘记密码</Link> */}
              <a onClick={this.forgetPwd} className={styles['fm-forgetPwd']}>
                忘记密码
              </a>
              <Button
                type="primary"
                loading={submitting}
                onClick={this.handleSubmit}
                className={styles['fm-btn']}
              >
                登录
              </Button>
            </FormItem>
            <FormItem>
              <div className={styles['info-tip']}>
                <InfoCircleOutlined style={{ marginRight: '10px', fontSize: '16px' }} />
                <h5>由于信息安全要求，您的账号可能因为未绑定邮箱、账号超期未登录等原因被锁定，请及时联系管理员</h5>
              </div>
            </FormItem>
          </Form>

        </div>
        <UpdatePassword
          dispatch={dispatch}
          visible={login.updatePasswordModal}
          // firstLogin={firstLogin && firstLogin}
          accountName={accountName}
          changeVisible={() =>
            dispatch({
              type: "login/save",
              payload: { updatePasswordModal: false },
            })
          }
          fetchCode={this.fetchCode}
        />
        <ValidateEmial
          accountName={accountName}
          validatorEmailOpen={login.validatorEmailOpen}
          dispatch={dispatch}
          fetchCode={this.fetchCode}
        />
        <BoundEmail
          accountName={accountName}
          bindEmailOpen={login.bindEmailOpen}
          dispatch={dispatch}
          fetchCode={this.fetchCode}
        />
      </div>
    );
  }
}

export default connect(({ login, loading }: any) => ({
  login,
  submitting: loading.effects['login/login'],
}))(Login);
